package com.springboot.manager.filter;


import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class CorsFilter implements Filter {


    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Content-Type, Accept, Access-Token,token");
        /*
         *   过虑 OPTIONS 请求
         *   前后端分离项目，前端请求会判断是否为复杂请求
         *   如果为复杂请求，会第一遍走options请求，第二遍才会走post 请求
         *   所以此处需要在options 请求时，直接赋值状态为ok，然后返回。
         *   否则前端的options请求会报CORS请求
         */
        String type = request.getMethod();
        if (type.toUpperCase().equals("OPTIONS")) {
            response.setStatus(HttpServletResponse.SC_OK);
            return;
        }
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {
    }

    public void destroy() {
    }

}
